
var http = require('../..//utils/httpHelper.js')
var util = require('../../utils/util.js')
var sta = require("../../utils/statistics.js");
var config = require('../../config.js')
//获取应用实例
var app = getApp()
Page({
  data: {
    allGoods:{},
    sumPrice:0,
    address:{},
    couponArray:[], //优惠券
    multiArray: ["快递","EMS","平邮","商家配送","自提"],
    objectArray: ["express", "ems", "surface","distribution","self"],
    objectCouponArray: [],
    couponList: [],
    couponPrice:0,
    pindex:0,
    cindex:0,
    couponIndex:0,
    shipping_type:'express',
    coupon:'0-0-0',
    postPrice:0
  },
  onLoad: function () {
    var that = this;
    sta();
    var sumPrice=0;
    var allGoods = wx.getStorageSync("allGoods");
    if (allGoods && allGoods.length > 0) {
      for (var i = 0; i < allGoods.length; i++) {
        var price = parseFloat(allGoods[i].sku ? allGoods[i].sku.price : allGoods[i].price);
        allGoods[i].price = price;
        var count = allGoods[i].buycount;
        price = util.accMul(price, count);
        sumPrice = util.accAdd(sumPrice, price);
      }
      http.request('/cart/add', {"carList":allGoods},function(res){

      });
      that.setData({
        allGoods: allGoods,
        sumPrice: sumPrice
      });
    }
    that.getDefaultAddress();
    that.initExpress(0);

    that.getMyCoupons();
	
  },
  onShow:function (){
	  
  },
  getDefaultAddress:function(){
      //获取地址
      var that = this;
      http.request("/customer/getAddrInfo" ,{},function(res){
        if(res.data.code == 0){
          that.setData({
            address:res.data.data,
            is_address:true}
          );
        }
      });
  },
  payOrderSuccess:function(orderid,status,callback){
		var data = {
		  id:orderid,
		  status:status
		};
		http.request("/order/updateOrder" ,data,function(res){
			if(res.data.code == 0 && res.data.msg == 'success'){
				//订单支付成功
				  typeof callback == "function" && callback(res.data.data)
			}else{
				//订单支付失败
				  typeof callback == "function" && callback('')
			}  
		})
  },
  toAddress:function(){
      wx.navigateTo({url: '/pages/select-address/index'})
  },
  addAddress:function(){
	   wx.navigateTo({url:"/pages/address-add/index?id=0"})
  },
  settlement:function (){
    var that = this;
    //检查地址是否为空
    if(this.data.address == ""){
        wx.showModal({
            title: '提示',
            content: '请您先添加邮寄地址！',
            success: function(res) {
              if (res.data.confirm) {
                  that.toAddress();
              }
              return;
            }
        })
    }
    //继续生成订单
    var addressid = this.data.address.address_id;
    var postIndex=this.data.cindex;
    var couponIndex=this.data.couponIndex;
    if(this.data.objectCouponArray.length>0){
      var coupon_info = this.data.objectCouponArray[couponIndex];
      var coupon=coupon_info.id+"-"+coupon_info.name+"-"+coupon_info.money;
    }
    if(addressid>0){
      var data ={
        address_id:addressid,
        payamount:that.data.sumPrice,
        post_fee: that.data.postPrice,
		    shipping_type:this.data.objectArray[postIndex],
        coupon:coupon,
        message:that.data.message,
        bidcmsid:wx.getStorageSync('bidcms_id')
      };
      
      http.request("/order/create" ,data,function(res){
        if(res.data.code == 0 && res.data.msg == 'success'){
          //订单创建成功
          if(res.data.orderid != ''){
            try{
              wx.removeStorageSync('allGoods');
            }catch(e){
              console.log('清空购物车失败');
            }
            wx.showToast({
              title: '下单成功',
              icon: 'success',
              duration: 1000
            });
            wx.redirectTo({
              url: '/pages/order/detail/index?id=' + res.data.orderid 
            });
          }
        }else{
          //订单创建失败
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 1000
          });
        }  
      });
    } else {
      wx.showToast({
        title: '添加配送地址',
        icon: 'success',
        duration: 1000
      });
    }
  },
  bindTextAreaInput: function(e) {
    this.setData({message:e.detail.value})
  },
  bindCouponChange: function(e) {
    var that = this;
    this.setData({
      couponIndex: e.detail.value,
      couponPrice: that.data.objectCouponArray[e.detail.value].money
    })
  },
  initExpress(e){
    var that = this;
    http.request('/order/freight', { address_id: this.data.address.address_id, shipping_type: this.data.objectArray[e] }, function (res) {
      if (res.data.code == 0) {
        that.setData({ postPrice: res.data.data.post_fee });
      }
    });
  },
  bindShippingChange: function (e) {
    this.initExpress(e.detail.value);
    this.setData({ cindex: e.detail.value });
  },
  getMyCoupons: function () {
    var that = this;
    http.request(
      '/order/discounts',
      {
        address_id: that.data.address.address_id,
        shipping_type: this.data.objectArray[that.data.cindex]
      },
      function (res) {
        if (res.data.code === 0) {
          var coupons = res.data.data.filter(entity => {
            return entity.money <= that.data.sumPrice;
          });

          if (coupons.length > 0) {
            var couponList = [];
            for (let i in coupons) {
              couponList.push(coupons[i]['name']);
            }
            console.log(couponList);
            that.setData({
              hasCoupons: true,
              objectCouponArray: coupons,
              couponList: couponList
            });
          }
        }
      }, -1)
  }
})
